#include "memberCenter.h"
#include "common.h"
#include "global.h"
#include "asgka_network.h"

#include <iostream>
using namespace std;

memberCenter::~memberCenter()
{
	std::map<std::string, singleMember *>::iterator it = m_all_member_list.begin();

	while (it != m_all_member_list.end())
	{
		delete it->second;
		m_all_member_list.erase(it++);
	}
}

const std::map<std::string, singleMember *> *memberCenter::getAddrofMemberList() const
{
	return (&m_all_member_list);
}

int memberCenter::getCountOfMember() const
{
	return m_all_member_list.size();
}

bool memberCenter::isMemberExisted(const std::string &name) const
{
	std::map<std::string, singleMember *>::const_iterator it = m_all_member_list.find(name);
	return (it != m_all_member_list.end());
}

singleMember *memberCenter::getMemberByName(const std::string &name) const
{
	std::map<std::string, singleMember *>::const_iterator it = m_all_member_list.find(name);
	if (it == m_all_member_list.end())
		return NULL;
	else 
		return it->second;
}

singleMember *memberCenter::createMember(const std::string &name, u_long net_addr)
{
	if (!isMemberExisted(name))
	{
		singleMember *newmember = new singleMember(name, net_addr);
		m_all_member_list.insert(stomvalType(name, newmember));
		cout << "Created member named " << name << endl; 
		return newmember;
	}
	return NULL;
}

singleMember *memberCenter::createMember(const std::string &name, u_long net_addr, SOCKET sock)
{
	if (!isMemberExisted(name))
	{
		singleMember *newmember = new singleMember(name, net_addr);
		newmember->setSocket(sock);
		m_all_member_list.insert(stomvalType(name, newmember));
		cout << "Created member named " << name << endl; 
		return newmember;
	}
	return NULL;
}

bool memberCenter::releaseMember(const std::string &name)
{
	std::map<std::string, singleMember *>::iterator it = m_all_member_list.find(name);
	if (it != m_all_member_list.end())
	{
		if (it->second->isAlone())
		{
			delete it->second;
			m_all_member_list.erase(it);
			return true;
		}
		return false;
	}
	return true;
}

void memberCenter::releaseAllMember()
{
	std::map<std::string, singleMember *>::iterator it = m_all_member_list.begin();

	while (it != m_all_member_list.end())
	{
		if (localname.compare(it->second->getMemberName()) == 0)
		{
			it++;
			continue;
		}

		if (it->second->isAlone())
		{
			delete it->second;
			m_all_member_list.erase(it++);
		}
		else
		{
			it++;
		}
	}
}

bool memberCenter::sendMessageToAllMember(messageBase *msg)
{
	bool flag = true;
	std::map<std::string, singleMember *>::const_iterator it = m_all_member_list.begin();
	
	for (; it != m_all_member_list.end(); it++)
	{
		if (localname.compare(it->second->getMemberName()) == 0)
			continue;

		flag = flag && sendMessageToMember_tcp(msg, it->second);
	}
	return flag;
}